package expressions.slogo;

import java.util.ArrayList;
import java.util.List;
import parsing.Token;
import exceptions.AssignmentException;
import exceptions.EvaluationException;
import expressions.Expression;
import expressions.IContext;
import expressions.Prefix;

@Token(regex = "to")
public class ToAssignment extends Prefix<Double>
{

    public ToAssignment()
    {
        super(3);
    }

    @Override
    public Double evaluate(IContext<Double> context)
    {
        if (!(children.get(0) instanceof UserCommand))
        {
            throw new AssignmentException(children.get(0));
        }

        UserCommand cmdName = (UserCommand) children.get(0);

        if (!(children.get(1) instanceof LeftBracket))
        {
            throw new EvaluationException();
        }

        LeftBracket argBracket = (LeftBracket) children.get(1);

        List<String> arguments = new ArrayList<String>();

        for (Expression<Double> grandchild : argBracket.getChildren())
        {
            if (!(grandchild instanceof Variable))
                throw new EvaluationException();

            Variable argument = (Variable) grandchild;

            arguments.add(argument.getVarName());
        }

        Expression<Double> method = children.get(2);

        UserCommand.defineCommand(cmdName.getName(),
                new UserCommand.MethodSignature(arguments, method));

        return 0D;
    }
}
